package com.xm.xmds1705083.service.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xm.xm.dto.ResultDto;
import com.xm.xm.dto.SearchDto;
import com.xm.xm.util.BeanUtils;
import com.xm.xm.util.DateUtils;
import com.xm.xm.util.ErrorCode;
import com.xm.xm.util.ValidateUtils;
import com.xm.xmds1705083.service.dto.DuoduoParkDto;
import com.xm.xmds1705083.service.dto.DuoduoPassLogDto;
import com.xm.xmds1705083.service.mapper.*;
import com.xm.xmds1705083.service.mapper.DuoduoParkMapper;
import com.xm.xmds1705083.service.mapper.DuoduoPassLogMapper;
import com.xm.xmds1705083.service.mapper.DuoduoPayInfoMapper;
import com.xm.xmds1705083.service.mapper.DuoduoPaymentRecordsMapper;
import com.xm.xmds1705083.service.model.*;
import com.xm.xmds1705083.service.model.DuoduoCoupon;
import com.xm.xmds1705083.service.model.DuoduoCouponRecords;
import com.xm.xmds1705083.service.model.DuoduoPark;
import com.xm.xmds1705083.service.model.DuoduoPassLog;
import com.xm.xmds1705083.service.model.DuoduoPayInfo;
import com.xm.xmds1705083.service.model.DuoduoPaymentRecords;
import com.xm.xmds1705083.service.model.DuoduoUserCar;
import com.xm.xmds1705083.service.model.SocketEntity;
import com.xm.xmds1705083.service.netty.DeviceTCPServerHandler;
import com.xm.xmds1705083.service.service.DuoduoParkService;
import com.xm.xmds1705083.service.service.DuoduoPayInfoService;
import com.xm.xmds1705083.service.util.*;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.SocketChannel;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * 杭州新苗网络科技有限公司
 * @author meihf
 * @date 2017/06/14
 * @description
 */
@Service("duoduoParkService")
public class DuoduoParkServiceImpl extends ServiceImpl<DuoduoParkMapper,DuoduoPark> implements DuoduoParkService {

    private ReentrantLock lock = new ReentrantLock();

    private Logger logger = LoggerFactory.getLogger(DuoduoParkServiceImpl.class);

    @Autowired
    DuoduoParkMapper duoduoParkMapper;

    @Autowired
    DuoduoUserCarMapper duoduoUserCarMapper;

    @Autowired
    DuoduoBookingMapper duoduoBookingMapper;

    @Autowired
    DuoduoPassLogMapper duoduoPassLogMapper;

    @Autowired
    DuoduoCouponRecordsMapper duoduoCouponRecordsMapper;

    @Autowired
    DuoduoCouponMapper duoduoCouponMapper;

    @Autowired
    DuoduoPaymentRecordsMapper duoduoPaymentRecordsMapper;
    @Autowired
    DuoduoPayInfoService duoduoPayInfoService;
    @Autowired
    DuoduoPayInfoMapper duoduoPayInfoMapper;

    @Autowired
    DuoduoPayNoticeMapper duoduoPayNoticeMapper;



    @Override
    public ResultDto closeParks(SearchDto searchDto) {
        ResultDto resultDto = new ResultDto();
        JSONObject filed = searchDto.getFiled();
        searchDto.setPageNo((searchDto.getPageNo()-1)*searchDto.getPageSize());
        try {
            if (!filed.has("lng") || !filed.has("lat")){
                resultDto.setMsg(ErrorCode.E10011);
                resultDto.setCode(ErrorCode.C10011);
                return resultDto;
            }else {
                double lng = filed.getDouble("lng");
                double lat = filed.getDouble("lat");
                filed.put("pageNo",searchDto.getPageNo());
                filed.put("pageSize",searchDto.getPageSize());
                List<DuoduoParkDto> duoduoParkList = duoduoParkMapper.selectClosePark(filed);
                if (duoduoParkList.size()==0){
                    resultDto.setCode(ErrorCode.C11001);
                    resultDto.setMsg(ErrorCode.E11001);
                    return resultDto;
                }
                duoduoParkList.forEach((park)->{
                    double distance = CoordinateConvert.getDistance(lat,lng,park.getLatitude(),park.getLongitude());
                    //筛选方圆十公里的停车场
                    if (distance<=10000){
                        park.setDistance(distance);
                    }
                });
                //comparing默认是从低到高排序，后面加reversed是反转排序方法
                Collections.sort(duoduoParkList, Comparator.comparing(DuoduoParkDto::getDistance));
                if (duoduoParkList.size()>4){
                    List<DuoduoParkDto> duoduoParkDtoList = duoduoParkList.subList(0,4);
                    resultDto.setData(duoduoParkDtoList);
                }else {
                    resultDto.setData(duoduoParkList);
                }
                resultDto.setMsg("搜索成功");
            }
        }catch (RuntimeException e ){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }

    @Override
    public ResultDto findCloseByName(SearchDto searchDto) {
        ResultDto resultDto = new ResultDto();
        JSONObject filed = searchDto.getFiled();
        searchDto.setPageNo((searchDto.getPageNo()-1)*searchDto.getPageSize());
        try {
            if (!filed.has("lng") || !filed.has("lat") || !filed.has("parkName")){
                resultDto.setMsg(ErrorCode.E10011);
                resultDto.setCode(ErrorCode.C10011);
                return resultDto;
            }else {
                String parkName = filed.getString("parkName");
                Double lng = filed.getDouble("lng");
                Double lat = filed.getDouble("lat");
                filed.put("pageNo",searchDto.getPageNo());
                filed.put("pageSize",searchDto.getPageSize());
                filed.put("parkName",parkName);
                List<DuoduoParkDto> duoduoParkDtoList = duoduoParkMapper.selectCloseParkByName(filed);
                if (duoduoParkDtoList.size()==0){
                    resultDto.setCode(ErrorCode.C11001);
                    resultDto.setMsg(ErrorCode.E11001);
                    return resultDto;
                }
                duoduoParkDtoList.forEach((park)->{
                    double distance = CoordinateConvert.getDistance(lat,lng,park.getLatitude(),park.getLongitude());
                    //筛选方圆十公里的停车场
                    if (distance<=10000){
                        park.setDistance(distance);
                    }
                });
                //comparing默认是从低到高排序，后面加reversed是反转排序方法
                Collections.sort(duoduoParkDtoList, Comparator.comparing(DuoduoParkDto::getDistance));
                if (duoduoParkDtoList.size()>4){
                    List<DuoduoParkDto> list = duoduoParkDtoList.subList(0,4);
                    resultDto.setData(list);
                }else {
                    resultDto.setData(duoduoParkDtoList);
                }
                resultDto.setMsg("查询成功!");
            }
        }catch (RuntimeException e ){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }




    @Override
    public ResultDto findCloseByNames(SearchDto searchDto) {
        ResultDto resultDto = new ResultDto();
        JSONObject filed = searchDto.getFiled();
        searchDto.setPageNo((searchDto.getPageNo()-1)*searchDto.getPageSize());
        try {
            if (!filed.has("parkName")){
                resultDto.setMsg(ErrorCode.E10011);
                resultDto.setCode(ErrorCode.C10011);
                return resultDto;
            }else {
                String parkName = filed.getString("parkName");
                filed.put("pageNo",searchDto.getPageNo());
                filed.put("pageSize",searchDto.getPageSize());
                filed.put("parkName",parkName);
                List<DuoduoParkDto> duoduoParkDtoList = duoduoParkMapper.selectCloseParkByNames(filed);
                if (duoduoParkDtoList.size()==0){
                    resultDto.setCode(ErrorCode.C11001);
                    resultDto.setMsg(ErrorCode.E11001);
                    return resultDto;
                }
                /*duoduoParkDtoList.forEach((park)->{
                    double distance = CoordinateConvert.getDistance(lat,lng,park.getLatitude(),park.getLongitude());
                    //筛选方圆十公里的停车场
                    if (distance<=10000){
                        park.setDistance(distance);
                    }
                });*/
                //comparing默认是从低到高排序，后面加reversed是反转排序方法
              /*  Collections.sort(duoduoParkDtoList, Comparator.comparing(DuoduoParkDto::getDistance));*/
                if (duoduoParkDtoList.size()>4){
                    List<DuoduoParkDto> list = duoduoParkDtoList.subList(0,4);
                    resultDto.setData(list);
                }else {
                    resultDto.setData(duoduoParkDtoList);
                }
                resultDto.setMsg("查询成功!");
            }
        }catch (RuntimeException e ){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }

    @Override
    public ResultDto findCloseByAddress(SearchDto searchDto) {
        ResultDto resultDto = new ResultDto();
        searchDto.setPageNo((searchDto.getPageNo()-1)*searchDto.getPageSize());
        JSONObject filed = searchDto.getFiled();
        try {
            if (!filed.has("lng") || !filed.has("lat") || !filed.has("address")){
                resultDto.setMsg(ErrorCode.E10011);
                resultDto.setCode(ErrorCode.C10011);
                return resultDto;
            }else{
                String address = filed.getString("address");
                double lat = filed.getDouble("lat");
                double lng = filed.getDouble("lng");
                filed.put("address",address);
                filed.put("pageNo",searchDto.getPageNo());
                filed.put("pageSize",searchDto.getPageSize());
                List<DuoduoParkDto> duoduoParkDtoList = duoduoParkMapper.selectCloseParkByAddress(filed);
                if (duoduoParkDtoList.size()==0){
                    resultDto.setCode(ErrorCode.C11001);
                    resultDto.setMsg(ErrorCode.E11001);
                    return resultDto;
                }

                duoduoParkDtoList.forEach((park)->{
                    double distance = CoordinateConvert.getDistance(lat,lng,park.getLatitude(),park.getLongitude());
                    //筛选方圆十公里的停车场
                    if (distance<=10000){
                        park.setDistance(distance);
                    }
                });
                //comparing默认是从低到高排序，后面加reversed是反转排序方法
                Collections.sort(duoduoParkDtoList, Comparator.comparing(DuoduoParkDto::getDistance));
                if (duoduoParkDtoList.size()>4){
                    List<DuoduoParkDto> list = duoduoParkDtoList.subList(0,4);
                    resultDto.setData(list);
                }else {
                    resultDto.setData(duoduoParkDtoList);
                }
                resultDto.setMsg("查询成功");
            }
        }catch (RuntimeException e ){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }

    @Override
    public ResultDto findPrivilege(SearchDto searchDto) {
        ResultDto resultDto = new ResultDto();
        JSONObject filed = searchDto.getFiled();
        searchDto.setPageNo((searchDto.getPageNo()-1)*searchDto.getPageSize());
        try {
            if (!filed.has("lng") || !filed.has("lat")){
                resultDto.setMsg(ErrorCode.E10011);
                resultDto.setCode(ErrorCode.C10011);
                return resultDto;
            }else{
                double lng = filed.getDouble("lng");
                double lat = filed.getDouble("lat");
                filed.put("pageNo",searchDto.getPageNo());
                filed.put("pageSize",searchDto.getPageSize());
                List<DuoduoParkDto> duoduoParkList = duoduoParkMapper.selectPrivilege(filed);
                if (duoduoParkList.size()==0){
                    resultDto.setCode(ErrorCode.C11001);
                    resultDto.setMsg(ErrorCode.E11001);
                    return resultDto;
                }
                duoduoParkList.forEach((park)->{
                    double distance = CoordinateConvert.getDistance(lat,lng,park.getLatitude(),park.getLongitude());
                    //筛选方圆十公里的停车场
                    if (distance<=10000){
                        park.setDistance(distance);
                    }
                });
                //comparing默认是从低到高排序，后面加reversed是反转排序方法
                Collections.sort(duoduoParkList, Comparator.comparing(DuoduoParkDto::getDistance));
                resultDto.setData(duoduoParkList);
                resultDto.setMsg("搜索成功");
            }
        }catch (RuntimeException e ){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }

    @Override
    public ResultDto findById(SearchDto searchDto) {
        ResultDto resultDto = new ResultDto();
        JSONObject filed = searchDto.getFiled();
        searchDto.setPageNo((searchDto.getPageNo()-1)*searchDto.getPageSize());
        try {
            if (!filed.has("parkId")|| !filed.has("lng")||!filed.has("lat")){
                resultDto.setMsg(ErrorCode.E10011);
                resultDto.setCode(ErrorCode.C10011);
                return resultDto;
            }else{
                long parkId = filed.getLong("parkId");
                double lng = filed.getDouble("lng");
                double lat = filed.getDouble("lat");
                DuoduoPark duoduoPark = duoduoParkMapper.selectById(parkId);
                if (duoduoPark==null){
                    resultDto.setCode(ErrorCode.C11001);
                    resultDto.setMsg(ErrorCode.E11001);
                    return resultDto;
                }else {
                    //计算距离
                    DuoduoParkDto duoduoParkDto = BeanUtils.copy(duoduoPark,DuoduoParkDto.class);
                    duoduoParkDto.setDistance(CoordinateConvert.getDistance(lat,lng,duoduoParkDto.getLatitude(),duoduoParkDto.getLongitude()));
                    resultDto.setData(duoduoParkDto);
                    resultDto.setMsg("搜索成功！");
                }
            }
        }catch (RuntimeException e ){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }

    @Override
    public ResultDto findMyCarPosition(SearchDto searchDto) {
        ResultDto resultDto = new ResultDto();
        JSONObject filed = searchDto.getFiled();
        searchDto.setPageNo((searchDto.getPageNo()-1)*searchDto.getPageSize());
        try {
            if (!filed.has("lng") || !filed.has("lat")){
                resultDto.setMsg(ErrorCode.E10011);
                resultDto.setCode(ErrorCode.C10011);
                return resultDto;
            }
            double lng = filed.getDouble("lng");
            double lat = filed.getDouble("lat");
            //这里应该先查预约再查停车
            List<DuoduoParkDto> duoduoParkDtoList = duoduoBookingMapper.selectBookingList(searchDto);
            if (duoduoParkDtoList.size()==0){
                EntityWrapper entityWrapper = new EntityWrapper();
                entityWrapper.where(" userId={0} and isDelete=0",searchDto.getAppUserId());
                List<DuoduoUserCar> duoduoUserCarList = duoduoUserCarMapper.selectList(entityWrapper);
                if (duoduoUserCarList.size()==0){
                    resultDto.setCode(ErrorCode.C11001);
                    resultDto.setMsg(ErrorCode.E11001);
                    return resultDto;
                }
                String mediaNo = duoduoUserCarList.get(0).getMediaNo();
                JSONObject param = new JSONObject();
                param.put("mediaNo",mediaNo);
                DuoduoParkDto duoduoParkDto = duoduoParkMapper.findMyCarPosition(param);
                if (duoduoParkDto==null){
                    //为空
                    resultDto.setCode(ErrorCode.C11001);
                    resultDto.setMsg(ErrorCode.E11001);
                    return resultDto;
                }else {
                    duoduoParkDto.setDistance(CoordinateConvert.getDistance(lat,lng,duoduoParkDto.getLatitude(),duoduoParkDto.getLongitude()));
                    resultDto.setData(duoduoParkDto);
                    resultDto.setMsg("查询成功");
                }
            }else {
                DuoduoParkDto parkDto = duoduoParkDtoList.get(0);
                parkDto.setDistance(CoordinateConvert.getDistance(lat,lng,parkDto.getLatitude(),parkDto.getLongitude()));
                resultDto.setData(parkDto);
                resultDto.setMsg("查询成功");
            }
        }catch (RuntimeException e ){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }


    /**
     *   1.从数据库判断是否支付成功
     *   2.如果没成功，直接socket 查询费用
     *   3.socket 处理
     * */
    @Override
    public ResultDto getTotalMoney(SearchDto searchDto) {
        lock = new ReentrantLock();
        lock.lock();

        ResultDto resultDto = new ResultDto();
        JSONObject filed = searchDto.getFiled();
        searchDto.setPageNo((searchDto.getPageNo()-1)*searchDto.getPageSize());
        try {
            //查询有没有需要支付的费用
            //先查车牌
          /*  EntityWrapper wrapper = new EntityWrapper();
            wrapper.where(" userId={0} and isDelete=0",searchDto.getAppUserId());
            List<DuoduoUserCar> duoduoUserCarList = duoduoUserCarMapper.selectList(wrapper);
            if (duoduoUserCarList.size()==0){
                resultDto.setCode(ErrorCode.C11001);
                resultDto.setMsg(ErrorCode.E11001);
                return resultDto;
            }*/
            EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.where(" type=2 and mediaNo={0} ", "浙A1234567"); //duoduoUserCarList.get(0).getMediaNo()
            //现在只有一辆车，所以只有一条记录 如果两条报错
            List<DuoduoPassLog> duoduoPassLogList = duoduoPassLogMapper.selectList(entityWrapper);
            DuoduoPassLog duoduoPassLog = duoduoPassLogList.get(0);
          /*  EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.where(" type=2 and mediaNo={0} ",duoduoUserCarList.get(0).getMediaNo());
            //现在只有一辆车，所以只有一条记录 如果两条报错
            List<DuoduoPassLog> duoduoPassLogList = duoduoPassLogMapper.selectList(entityWrapper);
            if (duoduoPassLogList.size()==0){
                resultDto.setCode(ErrorCode.C11001);
                resultDto.setMsg(ErrorCode.E11001);
                return resultDto;
            }else if (duoduoPassLogList.size()>1){
                resultDto.setCode(GlobalError.C11027);
                resultDto.setMsg(GlobalError.E11027);
                return resultDto;
            }else {*/
            //DuoduoPassLog duoduoPassLog = duoduoPassLogList.get(0);
//                先查有没有缴费记录
            EntityWrapper recordEntity = new EntityWrapper();
            recordEntity.where(" inputTime = {0} and mediaNo={1} ",duoduoPassLog.getInputTime(),duoduoPassLog.getMediaNo());
            List<DuoduoPaymentRecords> paymentRecords = duoduoPaymentRecordsMapper.selectList(recordEntity);
            if (paymentRecords.size()!=0){
                resultDto.setCode(GlobalError.C11029);
                resultDto.setMsg(GlobalError.E11029);
                return resultDto;
            }
            //获取停车场信息
//                List<DuoduoPark> duoduoParkList = duoduoParkMapper.selectList(new EntityWrapper<DuoduoPark>().where(" id={0} ",duoduoPassLog.getParkId()));
//                if (duoduoParkList.size()==0){
//                    resultDto.setCode(GlobalError.C11028);
//                    resultDto.setMsg(GlobalError.E11028);
//                    return resultDto;
//                }
//
            JSONObject jsonObject  = new JSONObject();
            jsonObject.put("datasrc", ProjectUtils.projectName);
            jsonObject.put("inputType", "00");
            jsonObject.put("mediaNo", duoduoPassLog.getMediaNo() ); //duoduoPassLog.getMediaNo()
            jsonObject.put("rsv1","");
            jsonObject.put("rsv2", "" );
            SocketEntity socketEntity = new SocketEntity(41 ,  1, duoduoPassLog.getParkId()  , RandomStringUtils.getRandomString(8),0 , jsonObject.toString());
            Runnable sendTask = new Runnable() {
                @Override
                public void run() {
                    sendTaskLoop:
                    try{
                        Map<String, ChannelHandlerContext> map = GatewayService.getChannels();
                        Iterator<String> it = map.keySet().iterator();
                        while (it.hasNext()) {
                            String key = it.next();
                            ChannelHandlerContext ctx = map.get(key);
                            System.out.println("请求停车费用数据:"+socketEntity.toString());
                            ctx.writeAndFlush(socketEntity.EnCode());
                        }
                    }catch(Exception e){break sendTaskLoop;}
                }
            };
            new Thread(sendTask).start();

            //DeviceTCPServerHandler.SendMsgToALL(socketEntity);

            //-- 检查 socket 是否告知 缴费金额相关数
            int i = 0;
            Double carFeeMoney = 0.0;
            int parkCount = 0;
            while (true){
                if( i > 10 ) break; // 超时导致数据发送失败
                // 查询数据库 是否存在
                EntityWrapper entityWrapper1 = new EntityWrapper();
                entityWrapper1.where(" mediaNo = {0} ", duoduoPassLog.getMediaNo());
                DuoduoPayInfo duoduoPayInfo =  duoduoPayInfoService.selectOne(entityWrapper1);
                if( duoduoPayInfo != null && duoduoPayInfo.getResult().equals("00") ){
                    //  -- 检索成功
                    carFeeMoney = duoduoPayInfo.getPaidAmount().doubleValue() ;
                    parkCount = duoduoPayInfo.getTimeCount();
                    break ;
                }
                i++ ;
                Thread.sleep(600);
            }

            //去掉优惠券的优惠
            //先查领取记录
            EntityWrapper entity = new EntityWrapper();
            entity.where(" userId={0} and isUsed=0 ",searchDto.getAppUserId()).orderBy("createTime",false);
            RowBounds rowBounds = new RowBounds(searchDto.getPageNo(),searchDto.getPageSize());
            List<DuoduoCouponRecords> duoduoCouponRecordsList = duoduoCouponRecordsMapper.selectPage(rowBounds,entity);
            DuoduoPassLogDto duoduoPassLogDto = BeanUtils.copy(duoduoPassLog,DuoduoPassLogDto.class);
//                String times[] = DateUtil.secToTime(duoduoPassLogDto.getParkCount()).split(":");
            DuoduoPark duoduoPark = duoduoParkMapper.selectById( duoduoPassLog.getParkId());
            duoduoPassLogDto.setBillRule(duoduoPark.getBillRule());
//                int coll = (Integer.parseInt(times[1])>0?1:0)+Integer.parseInt(times[0]);
//                float count = duoduoPark.getBillRule()*coll;
            if (duoduoCouponRecordsList.size()==0){
                //没有优惠券可用，那就直接返回
              //  duoduoPassLogDto.setAmount(carFeeMoney);
                duoduoPassLogDto.setAmount(0.01);
            }else {
                //如果不为空取最近的一条
                //再看领取的优惠券是否过期如果没有过期就获取,有过期的就进行剔除
                List<DuoduoCouponRecords> duoduoCouponRecords = duoduoCouponRecordsList.stream().filter((duoduoCouponRecord ->
                        duoduoCouponMapper.selectList(new EntityWrapper<DuoduoCoupon>().where(" id={0} ",duoduoCouponRecord.getCouponId())).get(0)
                                .getEndTime()>searchDto.getTime() && duoduoCouponMapper.selectList(new EntityWrapper<DuoduoCoupon>().where(" id={0} ",duoduoCouponRecord.getCouponId())).get(0)
                                .getParkId()==duoduoPark.getId()
                )).sorted(Comparator.comparing(DuoduoCouponRecords::getCreateTime).reversed()).collect(Collectors.toList());
                DuoduoCouponRecords records = duoduoCouponRecords.get(0);
                EntityWrapper couponWrapper = new EntityWrapper();
                couponWrapper.where(" id={0} ",records.getCouponId());
                DuoduoCoupon duoduoCoupon = (DuoduoCoupon) duoduoCouponMapper.selectList(couponWrapper).get(0);
//                    float counts = 0;
//                    counts = duoduoPark.getBillRule()*coll;
                if (carFeeMoney>duoduoCoupon.getMinMoney()){
                    carFeeMoney = carFeeMoney-duoduoCoupon.getMoney().floatValue();
                    duoduoPassLogDto.setAmount(Double.parseDouble(String.valueOf(carFeeMoney)));
                }else {
                    duoduoPassLogDto.setAmount(Double.parseDouble(String.valueOf(carFeeMoney)));
                }
            }
            duoduoPassLogDto.setParkCount(parkCount);
            resultDto.setData(duoduoPassLogDto);
           /* }*/
        }catch (RuntimeException e ){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        } catch (InterruptedException e) {
            e.printStackTrace();
            // 线程异常 \ 继续处理后续事件


        }finally {
            lock.unlock();
        }
        return resultDto;
    }

    @Override
    public ResultDto getParkInfo(SocketEntity entity) {
        ResultDto resultDto = new ResultDto();
        JSONObject filed = new JSONObject();
        try {
            if (!filed.has("parkName") || !filed.has("addr")
                    ||!filed.has("surplusSpace") || !filed.has("totalSpace")
                    ||!filed.has("payTimeout") || !filed.has("outTimeout")
                    ||!filed.has("billRule") || !filed.has("result")){
                logger.info(ErrorCode.E10011);
            }else{
                JSONObject params = JSONObject.fromObject(entity.getParam());
                int parkId = Integer.parseInt(entity.getTermid());
                String parkName = params.getString("parkName");
                String addr = params.getString("addr");
                int surplusSpace = params.getInt("surplusSpace");
                int totalSpace = params.getInt("totalSpace");
                int payTimeout = params.getInt("payTimeout");
                int outTimeout = params.getInt("outTimeout");
                String billRule = params.getString("billRule");
                String result = params.getString("result");
                logger.info("getParkInfo result  "+result);
                if (result.equals("00")){
                    //库中有就更新，没有就新增
                    EntityWrapper entityWrapper = new EntityWrapper();
                    entityWrapper.where(" id={0}",parkId);
                    List<com.xm.xmds1705083.service.model.DuoduoPark> duoduoParks = duoduoParkMapper.selectList(entityWrapper);
                    com.xm.xmds1705083.service.model.DuoduoPark duoduoPark = new com.xm.xmds1705083.service.model.DuoduoPark();

                    duoduoPark.setAddress(addr);
                    duoduoPark.setCreateTime(DateUtils.getTimeSecondLong().intValue());
                    duoduoPark.setBillRule(Float.valueOf(billRule));
                    duoduoPark.setTotalSpace(totalSpace);
                    duoduoPark.setSurplusSpace(surplusSpace);
                    duoduoPark.setOutTimeout(outTimeout);
                    duoduoPark.setPayTimeout(payTimeout);
                    duoduoPark.setParkName(parkName);
                    if (duoduoParks.size()==0){
                        duoduoPark.setId(parkId);
                        int resultInsert = duoduoParkMapper.insert(duoduoPark);
                        if (ValidateUtils.isGreaterThan0(resultInsert)){
                            resultDto.setMsg("保存成功");
                        }else {
                            resultDto.setMsg(ErrorCode.E11004);
                            resultDto.setCode(ErrorCode.C11004);
                        }
                    }else {
                        int updateResult = duoduoParkMapper.updateById(duoduoPark);
                        if (ValidateUtils.isGreaterThan0(updateResult)){
                            resultDto.setMsg("修改成功");
                        }else {
                            resultDto.setMsg(ErrorCode.E11003);
                            resultDto.setCode(ErrorCode.C11003);
                        }
                    }

                }
            }
        }catch (RuntimeException e ){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }

    @Override
    public ResultDto getPayInfo(SocketEntity entity) {
        ResultDto resultDto = new ResultDto();
        JSONObject filed = new JSONObject();
        try {
            if (!filed.has("acountNo") || !filed.has("mediaNo")
                    ||!filed.has("inputTime") || !filed.has("currentTime")
                    ||!filed.has("timeCount") || !filed.has("amount")
                    ||!filed.has("discAmount") || !filed.has("paidAmount")
                    ||!filed.has("settType") || !filed.has("result")){
                logger.info(ErrorCode.E10011);
            }else{
                JSONObject parmas = JSONObject.fromObject(entity.getParam());
                String acountNo = parmas.getString("acountNo");
                String mediaNo = parmas.getString("mediaNo");
                String inputTime = parmas.getString("inputTime");
                String currentTime = parmas.getString("currentTime");
                int timeCount = parmas.getInt("timeCount");
                int amount = parmas.getInt("amount");
                int discAmount = parmas.getInt("discAmount");
                int paidAmount = parmas.getInt("paidAmount");
                String settType = parmas.getString("settType");
                String result = parmas.getString("result");
                //将缴费信息存到数据库中
                com.xm.xmds1705083.service.model.DuoduoPayInfo duoduoPayInfo = new com.xm.xmds1705083.service.model.DuoduoPayInfo();
                duoduoPayInfo.setAccountNo(acountNo);
                duoduoPayInfo.setAmout(amount);
                duoduoPayInfo.setDisAmount(discAmount);
                duoduoPayInfo.setPaidAmount(paidAmount);
                duoduoPayInfo.setTimeCount(timeCount);
                duoduoPayInfo.setSettType(settType);
                duoduoPayInfo.setResult(result);
                duoduoPayInfo.setMediaNo(mediaNo);
                duoduoPayInfo.setInputTime(inputTime);
                duoduoPayInfo.setCurrentTime(currentTime);
                int insertResult = duoduoPayInfoMapper.insert(duoduoPayInfo);
                if (ValidateUtils.isGreaterThan0(insertResult)){
                    resultDto.setMsg("保存成功");
                }else {
                    resultDto.setMsg(ErrorCode.E11004);
                    resultDto.setCode(ErrorCode.C11004);
                }
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }

    @Override
    public ResultDto savePayRecord(SearchDto searchDto) {
        ResultDto resultDto = new ResultDto();
        JSONObject filed = searchDto.getFiled();
        searchDto.setPageNo((searchDto.getPageNo()-1)*searchDto.getPageSize());
        try {
            if (!filed.has("accountNo")){
                resultDto.setMsg(ErrorCode.E10011);
                resultDto.setCode(ErrorCode.C10011);
                return resultDto;
            }else{
                String accountNo = filed.getString("accountNo");
                //根据accountNo查询payInfo
                DuoduoPayInfo duoduoPayInfo = duoduoPayInfoMapper.selectList(new EntityWrapper<DuoduoPayInfo>().where(" accountNo ")).get(0);
                //查询后存
                DuoduoPaymentRecords duoduoPaymentRecords = new DuoduoPaymentRecords();
                duoduoPaymentRecords.setAccountNo(accountNo);
                duoduoPaymentRecords.setPayType(6);
                duoduoPaymentRecords.setAmount(duoduoPayInfo.getPaidAmount().doubleValue());
                duoduoPaymentRecords.setInputTime(duoduoPayInfo.getInputTime());
                duoduoPaymentRecords.setOutputTime(duoduoPayInfo.getCurrentTime());
                duoduoPaymentRecords.setMediaNo(duoduoPayInfo.getMediaNo());
                duoduoPaymentRecords.setParkCount(duoduoPayInfo.getTimeCount());
                duoduoPaymentRecords.setUserId(searchDto.getAppUserId().intValue());
                duoduoPaymentRecordsMapper.insert(duoduoPaymentRecords);
                //插入后就发缴费通知给停车场系统
                JSONObject jsonObject  = new JSONObject();
                jsonObject.put("datasrc", ProjectUtils.projectName);
                jsonObject.put("accountNo", accountNo);
                jsonObject.put("amount", duoduoPayInfo.getPaidAmount());
                jsonObject.put("payType", "01");
                jsonObject.put("inputTime", duoduoPayInfo.getInputTime());
                jsonObject.put("parkCount", duoduoPayInfo.getTimeCount());
                jsonObject.put("currentTime", duoduoPayInfo.getCurrentTime());
                jsonObject.put("payTime", DateUtils.getNowDateTime(DateUtils.PATTERN_DATE_TIME_SIMPLE));
                //这里之后补上
                jsonObject.put("payAcountNo", DateUtils.getNowDateTime(DateUtils.PATTERN_DATE_TIME_ALL));
                jsonObject.put("mediaNo", duoduoPayInfo.getMediaNo()); //duoduoPassLog.getMediaNo()
                jsonObject.put("rsv1","");
                jsonObject.put("rsv2", "" );
                SocketEntity socketEntity = new SocketEntity(42 ,  1, duoduoPayInfo.getParkId()  , RandomStringUtils.getRandomString(8),0 , jsonObject.toString());
                Runnable sendTask = new Runnable() {
                    @Override
                    public void run() {
                        sendTaskLoop:
                        try{
                            Map<String, ChannelHandlerContext> map = GatewayService.getChannels();
                            Iterator<String> it = map.keySet().iterator();
                            while (it.hasNext()) {
                                String key = it.next();
                                ChannelHandlerContext ctx = map.get(key);
                                System.out.println("缴费通知:"+socketEntity.toString());
                                ctx.writeAndFlush(socketEntity.EnCode());
                            }
                        }catch(Exception e){break sendTaskLoop;}
                    }
                };
                new Thread(sendTask).start();

//                 再查出来
                int i = 0;
                while (true){
                    if( i > 10 ) {
                        if (i>20) break;
                        else {
                            //这时候要查询是否是不可控的原因没有获取到数据
                            JSONObject notice = new JSONObject();
                            notice.put("accountNo",accountNo);
                            notice.put("datasrc",ProjectUtils.projectName);
                            notice.put("mediaNo",duoduoPayInfo.getMediaNo());
                            notice.put("rsv1","");
                            notice.put("rsv2","");
                            SocketEntity noticeSocket = new SocketEntity(43 ,  1, duoduoPayInfo.getParkId()  , RandomStringUtils.getRandomString(8),0 , jsonObject.toString());
                            Runnable sendFindNoticeTask = new Runnable() {
                                @Override
                                public void run() {
                                    sendTaskLoop:
                                    try{
                                        Map<String, ChannelHandlerContext> map = GatewayService.getChannels();
                                        Iterator<String> it = map.keySet().iterator();
                                        while (it.hasNext()) {
                                            String key = it.next();
                                            ChannelHandlerContext ctx = map.get(key);
                                            System.out.println("网络不可控情况下查询缴费通知:"+noticeSocket.toString());
                                            ctx.writeAndFlush(noticeSocket.EnCode());
                                        }
                                    }catch(Exception e){break sendTaskLoop;}
                                }
                            };
                            new Thread(sendFindNoticeTask).start();
                        }
                        break;
                    } // 超时导致数据发送失败
                    // 查询数据库 是否存在
                    EntityWrapper entityWrapper1 = new EntityWrapper();
                    entityWrapper1.where(" account = {0} ", accountNo);
                    DuoduoPayNotice entity = new DuoduoPayNotice();
                    entity.setAccountNo(accountNo);
                    DuoduoPayNotice duoduoPayNotice =  duoduoPayNoticeMapper.selectOne(entity);
                    if( duoduoPayNotice != null && duoduoPayInfo.getResult().equals("00") ){
                        //  -- 检索成功
                        break ;
                    }
                    i++ ;
                    Thread.sleep(600);
                }
            }
            resultDto.setMsg("缴费通知成功！");
        }catch (RuntimeException e){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }catch (InterruptedException e){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }

    @Override
    public ResultDto searchParkInfoById(SearchDto searchDto) {
        ResultDto resultDto = new ResultDto();
        JSONObject filed = searchDto.getFiled();
        searchDto.setPageNo((searchDto.getPageNo()-1)*searchDto.getPageSize());
        try {
            int parkId = filed.getInt("parkId");
            JSONObject jsonObject  = new JSONObject();
            jsonObject.put("datasrc", ProjectUtils.projectName);
            jsonObject.put("rsv1","");
            jsonObject.put("rsv2", "" );
            SocketEntity socketEntity = new SocketEntity(40 ,  1, parkId  , RandomStringUtils.getRandomString(8),0 , jsonObject.toString());
            Runnable sendTask = new Runnable() {
                @Override
                public void run() {
                    sendTaskLoop:
                    try{
                        Map<String, ChannelHandlerContext> map = GatewayService.getChannels();
                        Iterator<String> it = map.keySet().iterator();
                        while (it.hasNext()) {
                            String key = it.next();
                            ChannelHandlerContext ctx = map.get(key);
                            System.out.println("根据id查询停车场信息:"+socketEntity.toString());
                            ctx.writeAndFlush(socketEntity.EnCode());
                        }
                    }catch(Exception e){break sendTaskLoop;}
                }
            };
            new Thread(sendTask).start();

            int i = 0;
            while (true){
                if( i > 10 ) break; // 超时导致数据发送失败
                // 查询数据库 是否存在
                DuoduoPark duoduoPark =  duoduoParkMapper.selectById(parkId);
                if( duoduoPark != null){
                    //  -- 检索成功
                    break ;
                }
                i++ ;
                Thread.sleep(600);
            }
        }catch (RuntimeException e ){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }catch (InterruptedException e){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }


    public static void main(String args[]) {
        double dis = CoordinateConvert.getDistance(30.2980739179,120.3181242943,30.308915,120.325295);
        System.out.println(UUID.randomUUID());
    }

}

